<?php
    
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Log;
use EasyWeChat\Factory;
use App\Handlers\WechatConfigHandler;
use Illuminate\Support\Facades\Cache;
use App\AdminUsers;
use App\User;
use EasyWeChat\Kernel\Messages\Text;

class WechatController extends Controller
{
    protected $wechat;

    public function __construct(WechatConfigHandler $wechat){
        $this->wechat = $wechat;
    }

    public function serve($account){
        $app = $this->wechat->app($account);
        $app->server->push(function($message) use ($app){
            switch ($message['MsgType']) {
                case 'event':
                    $openid = $message['FromUserName'];
                    if ($message['Event'] == 'subscribe') {
                        $user = User::where(['openid'=>$message['FromUserName']])->first();
                        if(!isset($user)){
                            $userService = $app->user->get($message['FromUserName']);
                            // Log::info($userService);
                            $info['name'] = $userService['nickname'];
                            $info['openid'] = $userService['openid'];
                            $info['avatar'] = $userService['headimgurl'];
                            $info['unionid'] = $userService['unionid'];
                            $info['created_at'] = date("Y-m-d H:i:s");
                            $result = User::insert($info);
                        }
                        return '欢迎关注 消防云平台！';
                    }
                    if ($message['Event'] == 'SCAN') {
                        $cacheKey = $openid.'_sn';
                        // Log::info($message['EventKey']);
                        Cache::put($cacheKey, $message['EventKey'], 3);   //有效期3分钟
                        // $url = url('wxClinet/userMyReceived');
                        // $content = "欢迎使用微型应急站\n当前智能柜ID为：".trim($message['EventKey'])."\n取件请点击:<a href=\"".$url."\">立即取件</a>";
                        $content = "欢迎使用微型应急站\n当前智能柜ID为：".trim($message['EventKey'])."\n按需点击所需功能！";
                        return new Text($content);
                    }
                    break;
                case 'text':
                    return '收到文字消息';
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                default:
                    return '收到其它消息';
                    break;
            }
        });
        $response = $app->server->serve();
        return $response;
    }

    public function oauth_callback($account)
    {
        $app = $this->wechat->app($account);
        $user = $app->oauth->user();
        session(['wechat_user' => $user->toArray()]);
        //不管在哪个页面检测用户登录状态，都要写入session值：target_url
        $targetUrl = session()->has('target_url') ? session('target_url') : '/' ;
        //header('location:'. $targetUrl);
        return redirect()->to($targetUrl);
    }
    
    
    public function getQrcode(){
        $app = $this->wechat->app(1);
        $result = $app->qrcode->forever('YJ19110002');
        $url = $app->qrcode->url($result['ticket']);
        $content = file_get_contents($url); // 得到二进制图片内容
        file_put_contents(__DIR__ . '/YJ19110002.jpg', $content); // 写入文件
        print_r($content);die;
    }
    
    public function menu(){
        $app = $this->wechat->app(1);
        $buttons = [
            [
		        "type" => "miniprogram",
		        "name" => "消防云系统",
		        "appid"  => "wx301bce58badb7cc3",
		        "url" => 'http://xbxfy.benpuji.com',
		        "pagepath" => "pages/authorize/authorize"
		    ],
		    [
		        "type" => "view",
                "name" => "微型应急站",
		        "url" => 'http://xbxfy.benpuji.com/api/yjgindex',
		      //  "pagepath" => "pages/authorize/authorize"
		    ]
        ];
        $res = $app->menu->create($buttons);  
        print_r($res);die;
    }
    
}
